from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from apps.app01.models import User
from .user_serializer import UserUpdateSerializer


class UserUpdateView(APIView):
    # authentication_classes = []
    def post(self, request):
        # 从 token 中获取用户 ID
        user_id = request.user['user_id']

        try:
            # 查找用户信息
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"status": "error", "message": "User not found."}, status=404)

        # 使用传入的数据更新用户信息
        serializer = UserUpdateSerializer(user, data=request.data, partial=True)  # partial=True 允许部分更新
        if serializer.is_valid():
            # 保存更新
            serializer.save()
            return Response({"status": "success", "message": "User information updated successfully."})
        else:
            # 返回验证失败的错误信息
            return Response({"status": "error", "message": serializer.errors}, status=400)
